<template>
  <path :d="path" class="link" :stroke="strokeColor"></path>
</template>

<script>
import { mapState } from 'vuex';
import * as chroma from 'chroma-js';
const prototype = require('../prototype');

function getPath(sx, sy, ex, ey) {
  const len = Math.sqrt((sx - ex) * (sx - ex) + (sy - ey) * (sy - ey));
  return `M ${sx} ${sy} C ${sx + 0.25 * len} ${sy} ${ex - 0.25 * len} ${ey} ${ex} ${ey}`;
}

export default {
  props: ['src', 'dst'],

  computed: {
    ...mapState(['nodes', 'dragEndPos']),

    path() {
      if (!this.dst) {
        const id = `${this.src.isInput ? 'in' : 'out'}_${this.src.nodeId}_${this.src.pinTitle}`;
        const rect = document.getElementById(id).getBoundingClientRect();
        const width = rect.right - rect.left;
        const height = rect.bottom - rect.top;

        if (this.src.isInput) {
          return getPath(this.dragEndPos.x, this.dragEndPos.y, rect.left + width * 0.5, rect.top + height * 0.5);
        } else {
          return getPath(rect.left + width * 0.5, rect.top + height * 0.5, this.dragEndPos.x, this.dragEndPos.y);
        }
      } else {
        const srcId = `out_${this.src.nodeId}_${this.src.pinTitle}`;
        const dstId = `in_${this.dst.nodeId}_${this.dst.pinTitle}`;
        const srcRect = document.getElementById(srcId).getBoundingClientRect();
        const dstRect = document.getElementById(dstId).getBoundingClientRect();
        const srcWidth = srcRect.right - srcRect.left;
        const srcHeight = srcRect.bottom - srcRect.top;
        const dstWidth = dstRect.right - dstRect.left;
        const dstHeight = dstRect.bottom - dstRect.top;
        return getPath(
          srcRect.left + srcWidth * 0.5,
          srcRect.top + srcHeight * 0.5,
          dstRect.left + dstWidth * 0.5,
          dstRect.top + dstHeight * 0.5
        );
      }
    },

    strokeColor() {
      const { isInput, nodeId, pinTitle } = this.src;
      const node = this.nodes.find((x) => x.id === nodeId);
      const pin = isInput
        ? node.inputs.find((x) => x.title === pinTitle)
        : node.outputs.find((x) => x.title === pinTitle);
      const color = prototype.typeColor(pin.type);
      const chartsColor = `var(--vscode-charts-${color}`;
      return chroma.valid(chartsColor) ? chartsColor : color;
    },
  },
};
</script>

<style scoped>
.link {
  fill: none;
  stroke-width: 3px;
}
</style>
